#include "double list.h"
LTNode* BuyListNode(LTDataType x) {
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}

	node->data = x;
	node->next = NULL;
	node->prev = NULL;
	return node;
}
LTNode* LTInit() {
	LTNode* phead = BuyListNode(0);
	phead->next = phead;
	phead->prev = phead;
}
void LTPushBack(LTNode* phead, LTDataType x) {
	assert(phead);
	LTNode* newnode = BuyListNode(x);
	LTNode* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}
void LTPopBack(LTNode* phead) {
	assert(phead);
	assert(phead->next != phead);
	LTNode* tail = phead->prev;
	LTNode* tailprev = tail->prev;
	tailprev->next= phead;
	phead->prev = tailprev;
	free(tail);
}
void LTPushFront(LTNode* phead, LTDataType x) {
	LTNode* newnode = BuyListNode(x);
	LTNode* first = phead->next;
	newnode->next = first;
	first->prev = newnode;
	phead->next = newnode;
	newnode->prev = phead;
}
void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->prev != phead);  
	LTNode* front = phead->next;
	LTNode* frontnext = front->next;
	frontnext->prev = phead;
	phead->next = frontnext;
	free(front);
}
void LTPrint(LTNode* phead) {
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead) {
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}
LTNode* LTFind(LTNode* phead, LTDataType x) {
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead) {
		if (x == cur->data) {
			return cur;
		}
	cur=cur->next;
	}
	return NULL;
}
void LTInsert(LTNode* pos, LTDataType x) {
	assert(pos);
	LTNode* newnode = BuyListNode(x);
	LTNode* newprev = pos->prev;
	newprev->next = newnode;
	newnode->prev = newprev;
	newnode->next = pos;
	pos->prev = newnode;
}
void LTErase(LTNode* pos) {
	assert(pos);
	LTNode* newprev = pos->prev;
	LTNode* newnext = pos->next;
	newprev->next =newnext;
	newnext->prev = newprev;
	free(pos);
}
bool LTEmpty(LTNode* phead) {
	assert(phead);
	return phead->next == phead;
}
size_t LTSize(LTNode* phead)
{
	assert(phead);

	size_t size = 0;
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		++size;
		cur = cur->next;
	}

	return size;
}

void LTDestroy(LTNode* phead)
{
	assert(phead);

	LTNode* cur = phead->next;
	while (cur != phead)
	{
		LTNode* next = cur->next;
		free(cur);

		cur = next;
	}

	free(phead);
	//phead = NULL;
}